/**
 * k-form-design 自定表单时的通用方法
 * 表单组件ref定义为ruleForm
 * formkeys定义为表单字段
 */
import { getAction } from '@/services/manage'
import { CURY_TYPE } from '@/store/mutation-types'
export default {
  props: {
    disableSubmit: Boolean
  },
  data() {
    return {
      model: {},
      form: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      confirmLoading: false,
      editType: '',
      insertAtIndex: null
    }
  },
  computed: {
    vxeTableOption() {
      const defaultToolbarConfig = {
        buttons: [
          { buttonRender: { name: 'VxeToolbarAdd', events: { click: this.handleAdd }, disabled: this.disableSubmit }},
          { buttonRender: { name: 'VxeToolbarDel', events: { click: this.batchDel }, disabled: this.disableSubmit }}
        ],
        perfect: true,
        'class-name': 'z-vxe-toolbar'
      }
      /*
      *customTableToolbar为页面需要自定义的toolbar配置
      *也可以直接在页面组件使用时直接定义属性覆盖该配置
      */
      const toolbarConfig = Object.assign({ }, defaultToolbarConfig, this.customTableToolbar)
      return {
        border: true,
        resizable: true,
        'keep-source': true,
        'max-height': 500,
        'edit-config': this.disableSubmit ? false : { trigger: 'click', mode: 'row', showStatus: true, autoClear: false },
        'checkbox-config': { checkMethod: () => !this.disableSubmit },
        toolbarConfig: toolbarConfig
      }
    }
  },
  methods: {
    getAllValidate() {
      const values = []
      if ((this.refKeys instanceof Array)) {
        this.refKeys.forEach(key => {
          const target = this.$refs[key]
          if (target) {
            target.$vnode.tag.indexOf('VxeGrid') >= 0 ? values.push(this.tableValidate(target, key)) : values.push(this.formValidate(target, key))
          }
        })
      }
      this.$refs.ruleForm && values.push(this.$refs.ruleForm.validate())
      return Promise.all(values)
    },
    formValidate(target, key) {
      return new Promise((resolve, reject) => {
        target.validate(valid => {
          if (!valid) {
            reject({ key })// 校验不通过返回对应tab
          }
          resolve(true)
        })
      })
    },
    tableValidate(target, key) { // 修改vxetable校验返回值与form一致
      return new Promise((resolve, reject) => {
        target.validate(true, err => {
          if (err) {
            reject({ key })// 校验不通过返回对应tab
          }
          resolve(true)
        })
      })
    },
    async handleAdd(key, target) {
      // 获取表格插入数据
      const insertData = typeof this.getInsertData === 'function' ? await this.getInsertData() : {}
      target.insertAt(insertData, this.insertAtIndex).then(({ row }) => {
        target.setEditRow(row)
      })
    },
    async batchDel(key, target) {
      try {
        typeof this.beforeBatchDel === 'function' && await this.beforeBatchDel()
        target.removeCheckboxRow()
        typeof this.afterBatchDel === 'function' && await this.afterBatchDel()
      } catch (error) {
        console.log(error)
      }
    },
    createdVxeTableData(tableKey, dataSource) { // 解决vxe-table数据无列字段时,编辑表格数据无法双向绑定bug
      const $table = this.$refs[tableKey]
      $table.createData(dataSource).then(list => {
        $table.loadData(list)
      })
    },
    setDataCrud(records) { // 设置提交数据脏数据状态
      const { insertRecords, removeRecords, updateRecords } = records
      insertRecords && insertRecords.forEach(item => {
        item.crudType = CURY_TYPE.SAVE
      })
      removeRecords && removeRecords.forEach(item => {
        item.crudType = CURY_TYPE.DELETE
      })
      updateRecords && updateRecords.forEach(item => {
        item.crudType = CURY_TYPE.UPDATE
      })
      return [].concat(insertRecords, removeRecords, updateRecords)
    },
    /** 查询某个tab的数据 */
    requestSubTableData(url, params, tab, success) {
      return getAction(url, params).then(res => {
        if (res.success) {
          tab.dataSource = res.result
        }
        typeof success === 'function' ? success(res) : ''
      })
    }
  },
  mounted() {
    // 回调表单设计器加载完成事件
    this.$nextTick(() => {
      this.$emit('init')
    })
  }
}

